package com.mmall.example.count;


import com.mmall.annoations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程安全的
 * Created by megan on 2018/3/18.
 */
@Slf4j
@ThreadSafe
public class CountExample2 {
    /** 请求数 **/
    public static int clientTotal = 5000;

    /** 同时并发执行线程数 **/
    public static int threadTotal = 200;

    /** 计数器 -> Atomic(线程安全) **/
    public static AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) throws  Exception{
        //定义一个线程池
        ExecutorService executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                60L, TimeUnit.SECONDS,
                new SynchronousQueue<>(), r -> new Thread(r,"测试线程(线程安全的)"));
        // 信号量，闭锁
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        // 模拟并发请求
        for(int i = 0; i < clientTotal; i ++){
            executorService.execute(() -> {
                try {
                    // 请求一个信号，如果信号量小于clientTotal，则阻塞
                    semaphore.acquire();
                    add();
                    // 释放一个信号
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.error("exception",e);
                }
                countDownLatch.countDown();
            });
        }
        // 阻塞直到countDown 的次数为threadTotal
        countDownLatch.await();
        // 关闭线程池
        executorService.shutdown();
        log.info("count:{}",count.get());
    }


    /**
     * 这个方法线程安全
     */
    private static void add(){
        count.incrementAndGet();
        // count.getAndIncrement();
    }




}
